package com.wct.ssmdemo.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description http请求前后监听
 * @date 2020/1/16 14:23
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {

    private static final String START_TIME = "requestStartTime";

    /*
     * 请求处理之前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求的url
        String url = request.getRequestURI();
        // 获取参数列表
        Map parameterMap = request.getParameterMap();
        if (!url.contains("/assets")) {
            log.info("request start. url:{}, params:{}", url, parameterMap.toString());
        }
        long start = System.currentTimeMillis();
        request.setAttribute(START_TIME, start);
        return true;
    }

    /*
     * 请求处理之后调用，正常处理成功才调用，处理过程中出异常后不调用
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    /*
     * 请求处理之后调用，不论处理是否成功都调用，处理过程中出异常后也调用
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 获取请求的url
        String url = request.getRequestURI();
        // 获取参数列表
        Map parameterMap = request.getParameterMap();
        // 查看请求处理时间
        long start = (Long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        if (!url.contains("/assets")) {
            log.info("request complete. url:{}, cost:{}", url, end - start);
        }
//        log.info("exception: ", ex);
        removeThreadLocalInfo();
    }

    public void removeThreadLocalInfo() {
        RequestHolder.remove();
    }
}
